#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <bits/stdc++.h>
#include <nlohmann/json.hpp>
#include <sqlite3.h>

using namespace std;
using json = nlohmann::json;
vector<vector<string>> alldata;
void Open_DatabaseFile(const char* filename, sqlite3** database) {
    int rc = sqlite3_open(filename, database);
    if (rc != SQLITE_OK) {
        std::cout << sqlite3_errmsg(*database) << std::endl;
        exit(0);
    }
}

static int callback(void *data, int argc, char **argv, char **azColName){
   int i;
   vector<string> choice;
   for(i=0; i<argc; i++){
        //printf("%d,%s = %s\n", i,azColName[i], argv[i] ? argv[i] : "NULL");
        string data= (char*)argv[i];
        choice.emplace_back(data);
   }
    alldata.emplace_back(choice);
   return 0;
}

int readgpkg(string& satid)
{
    sqlite3 *db_one;
    char *zErrMsg = 0;
    int rc;
    const char *sql;
    const char* data = "Callback function called";

   /* Open database */
   string path = "/home/dmf/test/ttzzbb/output/" + satid;
   const char* filename = path.c_str();
    rc = sqlite3_open(filename, &db_one);
    if( rc ){
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db_one));
        exit(0);
    }else{
        fprintf(stderr, "Opened database successfully\n");
    }

   /* Create SQL statement */
   string nn = "";
   for(int i = 0; i < satid.size(); i++){
        if(satid[i] != '.'){
            nn += satid[i];
        }
        else break;
    }
   string sentence = "SELECT * from " + nn;
    sql = sentence.c_str();
    
   /* Execute SQL statement */
    rc = sqlite3_exec(db_one, sql, callback, (void*)data, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL error: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        //fprintf(stdout, "Operation done successfully\n");
    }
    sqlite3_close(db_one);
    return 0;
}